package org.example.thread;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.example.util.ExceptionUtil;

/**
 * 说明:
 * Created on 2020/5/1 15:21
 *
 * @author tiancheng
 */
public abstract class ThreadTask implements Runnable {
    protected final Logger logger = LogManager.getLogger(getClass());
    // 线程名
    private final String name;

    //是否正在执行
    private volatile boolean isRunning = false;

    public String getName() {
        return name;
    }

    public ThreadTask(String name) {
        this.name = name;
    }

    /**
     * 执行命令
     */
    protected abstract void action();

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try {
            isRunning = true; // 设置为正在运行
            action();
        } catch (Exception e) {
            logger.error("{} 执行失败 error:{}:", this.name, ExceptionUtil.show(e));
        } finally {
            isRunning = false; // 任务完成后设置为不运行
        }
    }
}
